package com.cdtu.outtake.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdtu.outtake.dao.ShopMapper;
import com.cdtu.outtake.domain.Category;
import com.cdtu.outtake.dto.ShopDetailDto;
import com.cdtu.outtake.domain.Shop;
import com.cdtu.outtake.domain.User;
import com.cdtu.outtake.dto.ShopDto;
import com.cdtu.outtake.service.ICategoryService;
import com.cdtu.outtake.service.IProductService;
import com.cdtu.outtake.service.IShopService;
import com.cdtu.outtake.service.IStarService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author : shl
 * @Date 2024/3/20 19:23
 */
@Service
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop>
        implements IShopService {
    private final ICategoryService categoryService;
    private final IProductService productService;
    private final IStarService starService;

    @Override
    public List<Shop> getShopsBySchoolId(Long schoolId) {
        return this.baseMapper.selectList(new QueryWrapper<Shop>().eq("school_id", schoolId));
    }
    @Override
    public List<Shop> getShopsBySchoolIdAndConditions(Long schoolId, String keyword, boolean dineIn, boolean takeaway, boolean offlinePickUp) {
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        if (schoolId != null) {
            wrapper.eq("school_id", schoolId);
        }
        if (keyword != null && !keyword.isBlank()) {
            wrapper.like("name", keyword);
        }
        if (dineIn) {
            wrapper.eq("dine_in", true);
        }
        if (takeaway) {
            wrapper.eq("takeaway", true);
        }
        if (offlinePickUp) {
            wrapper.eq("offline_pick_up", true);
        }
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public Shop getShopById(Long shopId) {
        return baseMapper.selectById(shopId);
    }

    @Override
    public ShopDetailDto getShopDetailById(Long shopId) {
        Shop shop = getBaseMapper().selectById(shopId);
        ShopDto shopDto = ShopDto.toShopDto(shop);
        List<Category> categoryList = categoryService.getCategoriesByShopId(shopId).stream()
                .peek(category -> category.setProducts(productService.getProductsByCategoryId(category.getId())))
                .collect(Collectors.toList());
        shopDto.setCategories(categoryList);
        boolean star = false;
        if (StpUtil.isLogin()) {
            Long userId = ((User) (StpUtil.getSession().get("userInfo"))).getId();
            star = starService.isStar(userId, shopId);
        }
        return new ShopDetailDto(shopDto, star);
    }

    @Override
    public List<Shop> getStarShop() {
        return baseMapper.selectBatchIds(starService.getStarShopIds());
    }
}
